﻿using AutoMapper;
using B.S.Sterilizationcenter.Domain.yjb;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Writer.API.Appliaction.Commends.Yjb.ResultItemInf;
using B.S.Sterilizationcenter.Writer.API.FileNlog;
using MediatR;
using SqlSugar;

namespace B.S.Sterilizationcenter.Writer.API.Appliaction.CommandHandlers.Yjb.ResultItemInf
{
    public class AddResultItemInfoCommandHandlers : IRequestHandler<AddResultItemInfoCommand, ApiResult<int>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        private readonly Nolgs nolgs;

        public AddResultItemInfoCommandHandlers(ISqlSugarClient db, IMapper mapper, Nolgs nolgs)
        {
            this.db = db;
            this.mapper = mapper;
            this.nolgs = nolgs;
        }
        public async Task<ApiResult<int>> Handle(AddResultItemInfoCommand request, CancellationToken cancellationToken)
        {
            var startTime = DateTime.Now;
            try
            {
                ApiResult<int> result = new ApiResult<int>();
                var data = mapper.Map<ResultItemInfo>(request);
                result.Data = await db.Insertable(data).ExecuteCommandAsync();
                if (result.Data > 0)
                {
                    result.Code = ApiEnums.添加成功;
                    result.Msg = "添加成功";

                }
                else
                {
                    result.Code = ApiEnums.添加失败;
                    result.Msg = "添加失败";
                }
                return result;
            }

            catch (Exception)
            {

                throw;
            }
            finally
            {
                var endTime = DateTime.Now;

                var durationInDays = (endTime - startTime).Days;
                nolgs.GetNlogs(
                    request.ResultItem ?? "Unknow", "设备添加", "False", durationInDays, "异常信息"
                    );
            }
        }
    }
}
